/**
 * @Name:  ErrorBoundary
 * @Author:
 * @Desc:  页面崩溃渲染降级UI
 * @Date: 2021-01-14 14:55:55
 */

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { CrashPage } from "@/component";
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      path: ""
    };
  }
  static getDerivedStateFromError(error) {
    console.log("error===", error);
    //更新state 渲染降级UI
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.log("componentDidCatch===", error, info);
    this.setState({ hasError: true });
    window.onerror = null;
    return;
  }
  componentDidUpdate() {
    console.log("===", window.location.pathname, this.state.hasError);
    const newpath = window.location.pathname;
    const { path } = this.state;
    if (path !== newpath) {
      this.setState({ path: newpath, hasError: false });
    }
  }
  render() {
    console.log("errorbbbb==", this.state.hasError);
    if (this.state.hasError) {
      return <CrashPage />;
    }
    return this.props.children;
  }
}
export default withRouter(ErrorBoundary);
